package com.zhaowenhao.hello.demo.controller;

import com.zhaowenhao.hello.demo.service.IModifyService;
import com.zhaowenhao.hello.demo.service.IQueryService;
import com.zhaowenhao.hello.spring.framework.annotation.WHAutowired;
import com.zhaowenhao.hello.spring.framework.annotation.WHController;
import com.zhaowenhao.hello.spring.framework.annotation.WHRequestMapping;
import com.zhaowenhao.hello.spring.framework.annotation.WHRequestParam;
import com.zhaowenhao.hello.spring.framework.webmvc.servlet.WHModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 公布接口url
 */
@WHController
@WHRequestMapping("/web")
public class MyController {

    @WHAutowired
    IQueryService queryService;
    @WHAutowired
    IModifyService modifyService;

    @WHRequestMapping("/query")
    public WHModelAndView query(HttpServletRequest request, HttpServletResponse response,
                                @WHRequestParam("name") String name) {
        String result = queryService.query(name);
        return out(response, result);
    }

    @WHRequestMapping("/add*")
    public WHModelAndView add(HttpServletRequest request, HttpServletResponse response,
                              @WHRequestParam("name") String name, @WHRequestParam("addr") String addr) {
        String result = modifyService.add(name, addr);
        return out(response, result);
    }

    @WHRequestMapping("/remove")
    public WHModelAndView remove(HttpServletRequest request, HttpServletResponse response,
                                 @WHRequestParam("id") Integer id) {
        String result = modifyService.remove(id);
        return out(response, result);
    }

    @WHRequestMapping("/edit")
    public WHModelAndView edit(HttpServletRequest request, HttpServletResponse response,
                               @WHRequestParam("id") Integer id,
                               @WHRequestParam("name") String name) {
        String result = modifyService.edit(id, name);
        return out(response, result);
    }


    private WHModelAndView out(HttpServletResponse resp, String str) {
        try {
            resp.getWriter().write(str);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
